import axios, { type Method } from 'axios'
import { showToast } from 'vant'
import { useUserStore } from '../stores'
import router from '../router'
const baseURL = 'https://consult-api.itheima.net/'
const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL,
  timeout: 10000
})
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // console.log(router.currentRoute.value)
    // TODO 2. 携带token
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers['Authorization'] = `Bearer ${store.user.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)
// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    if (res.data?.code !== 10000) {
      showToast(res.data?.message || '业务失败')
      return Promise.reject(res.data)
    }
    // TODO 4. 摘取核心响应数据
    return res.data
  },
  (err) => {
    // TODO 5. 处理401错误
    if (err.response.status === 401) {
      // 清空个人信息
      const store = useUserStore()
      store.delUser()
      // 跳转到登录页
      router.push({
        path: '/login',
        query: {
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(err)
  }
)

// 请求工具函数
type Data<T> = {
  code: number
  message: string
  data: T
}

const request = <T>(url: string, method: Method, submitData?: object) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    // 如何区分拼接的属性是data还是params
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
    // params: submitData
    // data: submitData
  })
}
// type DemoType = {
//   name: string
//   age: number
// }
// request<DemoType>()

export { request, instance, baseURL }
